<template>
  <div class="upload-img-container">
    <!-- 图片预览区域 -->
    <div v-if="localImgUrl" class="img-preview-container">
      <el-image
        :src="localImgUrl"
        alt="Preview image"
        class="preview-image"
        fit="contain"
      />
      <el-button
        class="delete-btn"
        size="small"
        @click="handleDelete"
      >
        {{ t('sys.components.upload.delete') }}
      </el-button>
    </div>

    <!-- 上传区域 -->
    <div v-else class="upload-area" @click="handleUploadClick">
      <div class="upload-text">{{ t('sys.components.upload.clickToUploadImage') }}</div>
      <input
        ref="fileInput"
        type="file"
        accept="image/*"
        class="file-input"
        @change="handleFileChange"
      />
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue';
import { uploadSingleImageApi } from '@/api/upload/upload';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

// 定义props
const props = defineProps({
  imgUrl: {
    type: String,
    default: '',
    required: false
  }
});

// 定义事件
const emit = defineEmits(['update:imgUrl', 'change']);

// 本地状态
const localImgUrl = ref<string>(props.imgUrl);
const uploadLoading = ref<boolean>(false);
const errorMessage = ref<string>('');
const fileInput = ref<HTMLInputElement | null>(null);

// 监听props变化，同步到本地状态
watch(
  () => props.imgUrl,
  (newVal) => {
    localImgUrl.value = newVal;
  },
  { immediate: true }
);

// 触发文件选择
const handleUploadClick = () => {
  if (uploadLoading.value) return;
  fileInput.value?.click();
};

// 处理文件选择
const handleFileChange = async (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (!target.files || target.files.length === 0) return;

  const file = target.files[0];
  await handleFileUpload(file);

  // 重置input值，允许重复上传同一张图片
  target.value = '';
};

// 处理文件上传
const handleFileUpload = async (file: File) => {
  console.log(file);
  uploadLoading.value = true;
  errorMessage.value = '';

  try {
    const response = await uploadSingleImageApi(file);
    if (response && response.code === 0) {
      const imgUrl = response.data.fullPath;
      localImgUrl.value = imgUrl;
      // 触发事件通知父组件
      emit('update:imgUrl', imgUrl);
      emit('change', imgUrl);
    } else {
      throw new Error(response.data?.message || t('sys.components.upload.uploadFail'));
    }
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : t('sys.components.upload.uploadFail');
    console.error('图片上传失败:', error);
  } finally {
    uploadLoading.value = false;
  }
};

// 处理图片删除
const handleDelete = () => {
  localImgUrl.value = '';
  emit('update:imgUrl', '');
  emit('change', '');
};
</script>

<style scoped lang="scss">
.upload-img-container {
  width: 100%;
  min-height: 150px;
  position: relative;
}

.img-preview-container {
  width: 100%;
  height: 100%;
  border: 1px dashed #ccc;
  border-radius: 4px;
  position: relative;
  overflow: hidden;
}

.preview-image {
  // 将原100%尺寸修改为固定小尺寸
  width: 200px;  // 调整为合适的宽度
  height: 150px; // 调整为合适的高度
  object-fit: contain;
}

.delete-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  &:hover {
    background: rgba(0, 0, 0, 0.7);
  }
}

.upload-area {
  width: 100%;
  height: 150px; // 保持与预览图高度一致
  border: 1px dashed #ccc;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;

  &:hover {
    border-color: #409eff;
  }
}

.upload-icon {
  color: #409eff;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
}

.file-input {
  display: none;
}

.upload-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  text-align: center;
}
</style>
